import 'dart:ui';
import 'package:decimal/decimal.dart';
import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/widgets/shadow/kq_box_decoration.dart';
import 'package:kq_flutter_core_widget/widgets/shadow/kq_box_shadow.dart';
import 'package:kq_flutter_pad_widgets/config/kq_pad_global.dart';
import 'package:kq_flutter_pad_widgets/resources/images.dart';
import 'package:kq_flutter_pad_widgets/resources/kq_pad_theme_colors.dart';
import 'package:kq_flutter_pad_widgets/widgets/slider/kq_pad_slider_component_shape.dart';
import 'package:kq_flutter_pad_widgets/widgets/slider/kq_pad_slider_component_shape_image_builder.dart';
import 'package:kq_flutter_pad_widgets/widgets/slider/kq_pad_slider_track_shape.dart';

class KqPadSlider extends StatefulWidget {
  /// 滑杆高度
  final double? trackHeight;

  ///滑动回调
  final void Function(double sliderValue)? onChanged;

  ///结束时回调
  final void Function(double sliderValue)? onChangeEnd;

  ///开始时回调
  final void Function(double sliderValue)? onChangeStart;

  /// 最大值
  final double? min;

  /// 最小值
  final double? max;

  /// 默认值
  final double? defluatValue;

  /// 滑杆颜色
  final Color? activeColor;

  /// 滑块大小
  final Size? thumbShapeSize;

  /// 值
  final Widget? valueView;

  /// valueView的高度
  final double? valueViewHeight;

  /// valueView的宽度
  final double? valueViewWidth;

  /// valueView与slider的间距
  final double? viewSliderSpacing;

  /// 限制小数点后几位,默认2位
  final int? limitAfterNum;

  /// 滑块图片
  final String? thumbImg;

  /// 滑块是否可滑动，默认：true
  final bool enable;

  const KqPadSlider(
      {this.trackHeight,
      this.onChanged,
      this.onChangeEnd,
      this.onChangeStart,
      this.min = 0,
      this.max = 100,
      this.defluatValue = 0,
      this.activeColor,
      this.thumbShapeSize,
      this.thumbImg,
      this.valueView,
      this.valueViewHeight = 0,
      this.valueViewWidth = 0,
      this.viewSliderSpacing = 0,
      this.limitAfterNum = 2,
      this.enable = true,
      super.key});

  @override
  State<KqPadSlider> createState() => _KqPadSliderState();
}

class _KqPadSliderState extends State<KqPadSlider> {
  final GlobalKey _sliderKey = GlobalKey();
  double avalue = 0;
  double left = 0;
  double width = 0;
  int limitNum = 2;

  @override
  void initState() {
    super.initState();
    avalue = widget.defluatValue!;
    limitNum = widget.limitAfterNum!;
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      // print(timeStamp);
      final RenderBox renderBox =
          _sliderKey.currentContext?.findRenderObject() as RenderBox;
      width = renderBox.size.width;
      setState(() {
        left = getLeftSpacing(avalue);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      clipBehavior: Clip.none,
      children: [renderSlider(), renderValueWidget()],
    );
  }

  Widget renderValueWidget() {
    if (widget.valueView != null && widget.valueViewHeight != null) {
      double spacing = widget.viewSliderSpacing ?? 0;
      return Positioned(
          top: -widget.valueViewHeight! / 2 - spacing,
          left: left,
          child: widget.valueView!);
    }
    return Container();
  }

  Widget renderSlider() {
    if (widget.max != null) {
      if (avalue > widget.max!) {
        avalue = widget.max!;
      }
    }
    if (widget.min != null) {
      if (avalue < widget.min!) {
        avalue = widget.min!;
      }
    }
    return Positioned(
        key: _sliderKey,
        top: 0,
        left: 0,
        right: 0,
        child: Container(
          clipBehavior: Clip.none,
          height: widget.trackHeight ?? 6.dm,
          decoration: KqBoxDecoration(
              color: KqPadThemeColors.tabBarBgColor,
              borderRadius: BorderRadius.all(Radius.circular(20.dm)),
              boxShadow: [
                KqBoxShadow(
                    offset: Offset(1.dm, 1.dm),
                    blurRadius: 2.dm,
                    spreadRadius: 0,
                    color: KqPadThemeColors.shadowColor3,
                    inset: true),
                KqBoxShadow(
                    offset: Offset(-1.dm, -1.dm),
                    blurRadius: 3.dm,
                    spreadRadius: 0,
                    color: KqPadThemeColors.textWhite,
                    inset: true)
              ]),
          child: KqPadSliderComponentShapeImageBuilder(
            assertName: widget.thumbImg ?? Images.commonIcHuakuai28,
            package: widget.thumbImg != null ? null : KqPadGlobal.packageName,
            builder: (context, imageInfo) {
              return SliderTheme(
                data: SliderTheme.of(context).copyWith(
                  trackHeight: widget.trackHeight ?? 6.dm,
                  overlayShape: const RoundSliderOverlayShape(
                    overlayRadius: 0,
                  ),
                  thumbShape: KqPadSliderComponentShape(
                      image: imageInfo?.image,
                      sliderWidth: width,
                      size: widget.thumbShapeSize ?? Size(20.dm, 20.dm)),
                  trackShape: const KqPadSliderTrackShape(addHeight: 0),
                ),
                child: Slider(
                  value: avalue,
                  min: widget.min ?? 0,
                  max: widget.max ?? 100,
                  activeColor: widget.activeColor ?? const Color(0xFF46BDBE),
                  inactiveColor: Colors.transparent,
                  onChanged: widget.enable
                      ? (value) {
                          double r = realWithValue(value);
                          widget.onChanged?.call(r);
                        }
                      : (value) {},
                  onChangeEnd: widget.enable
                      ? (value) {
                          realWithValue(value);
                          double r = realWithValue(value);
                          widget.onChangeEnd?.call(r);
                        }
                      : (value) {},
                  onChangeStart: widget.enable
                      ? (value) {
                          widget.onChangeStart?.call(value);
                        }
                      : (value) {},
                ),
              );
            },
          ),
        ));
  }

  double getLeftSpacing(double value) {
    double space =
        ((value - widget.min!) / (widget.max! - widget.min!)) * width -
            widget.valueViewWidth! / 2.0;

    /// 处理接近0的偏移
    Size size = widget.thumbShapeSize ?? Size(20.dm, 20.dm);
    if (avalue <= widget.min!) {
      space = space + (size.width / 4);
    } else if (avalue >= widget.max!) {
      space = space - (size.width / 4);
    }
    return space;
  }

  double realWithValue(double value) {
    double v = value;
    int a = limitNum;
    while (a > 0) {
      a--;
      v = v * 10.0;
    }
    int i = v.round();
    double r = double.parse(i.toString());
    int b = limitNum;
    while (b > 0) {
      b--;
      r = r / 10.0;
    }

    setState(() {
      avalue = r;
      left = getLeftSpacing(r);
    });
    return r;
  }

  @override
  void didUpdateWidget(covariant KqPadSlider oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.defluatValue != widget.defluatValue) {
      avalue = widget.defluatValue ?? avalue;
    }
  }
}
